<?php
/**
 * Created by PhpStorm.
 * User: Asnyc
 * Date: 2017/12/28
 * Time: 8:44
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\User as UserModel;
use app\api\service\Token as TokenService;
use app\lib\validate\AddressNew;
use app\lib\exception\UserException;
use application\lib\exception\SuccessMessage;

class Address extends BaseController
{
    /**
     * @var array
     * 前置操作 检查scope
     */
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createOrUpdateAddress']
    ];


    /**
     * @return \think\response\Json
     * @throws UserException
     * 创建或者更新收货地址
     */
    public function createOrUpdateAddress(){
        $validate = new AddressNew();
        $validate->gocheck();
       // (new AddressNew())->gocheck();
        /**
         * 根据Token来获取UID
         * 根据UID来查找用户数据,判断用户是否存在,不存在则抛异常
         * 获取用户从客户端提交过来的地址信息
         * 根据用户地址信息是否存在,从而判断是添加地址还是新增地址
         */
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if(!$user){
            throw new UserException();
        }
        $dataArray = $validate->getDataByRule(input('post.')); //过滤数组
        $userAddress = $user->address;
        if(!$userAddress){
            $user->address()->save($dataArray); //新建
        }else{
            $user->address->save($dataArray); //更新
        }
        return json(new SuccessMessage(),201);
    }
}